package com.ttxs.gateway.config;

import com.ttxs.gateway.filter.AuthFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Order(-1)
@Configuration
public class GlobalErrorHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error(ex.getMessage(), ex);

        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        if(ex instanceof ResponseStatusException) {
            ResponseStatusException statusException = (ResponseStatusException) ex;
            return AuthFilter.error(response, statusException.getStatus(), "gateway: 请求【"+exchange.getRequest().getPath()+"】服务异常：" + statusException.getMessage());
        }
        return AuthFilter.error(response, response.getStatusCode(), "gateway: 请求【"+exchange.getRequest().getPath()+"】服务异常");
    }
}
